const express = require('express')
// 解析数据格式插件
const parse = require('body-parser')
const fs = require('fs')

// 解析token
const expressJwt = require('express-jwt')
const cors = require('cors')
const config = require('./config.js')

const app = express();

app.use(cors())

// 解析token中间件
app.use(expressJwt({secret:config.JwtSecret,algorithms:['HS256']}).unless({path:[/^\/api\//]}))
// 解析json或urlencoded格式数据
// app.use(parse.urlencoded({extended:false}))
// app.use(parse.json())
app.use(parse.json({limit: '4096kb'}));
app.use(parse.urlencoded({limit: '4096kb', extended: false}));


// 注册全局中间件
app.use((req,res,next)=>{
    res.cc = function(err,status = 1){
        res.send({
            status,
            message:err instanceof Error? err.message:err
        })
    }
    next();
})


// 不需要token的接口
const userRouter = require('./router/api/user.js')
const schArticle = require('./router/api/schArticle.js')
const trade = require('./router/api/trade.js')
const question = require('./router/api/question.js')
const search = require('./router/api/search.js')
const comment = require('./router/api/comments.js')
app.use('/api',userRouter)
app.use('/api',schArticle)
app.use('/api',trade)
app.use('/api',question)
app.use('/api',search)
app.use('/api',comment)
// 需要Token的接口
const ad_SetUserRouter = require('./router/admin/adminUser.js');
const ad_manager = require('./router/admin/manager.js')
const ad_schArt = require('./router/admin/schArticle.js')
const ad_trade = require('./router/admin/trade.js')
const ad_quetion = require('./router/admin/question.js')
const ad_comments = require('./router/admin/comments.js')
const { path } = require('express/lib/application')
app.use('/admin',ad_SetUserRouter)
app.use('/admin',ad_manager)
app.use('/admin',ad_schArt)
app.use('/admin',ad_trade)
app.use('/admin',ad_quetion)
app.use('/admin',ad_comments)


// ---错误处理
app.use((err,req,res,next)=>{
    if(err.name === 'UnauthorizedError') return res.send({
        status:err.status,
        message:'身份验证失败',
       
    })
    return res.send(err)
})
app.listen('8089',function(){
    console.log('Http://127.0.0.1:8089');
}) 